﻿using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using Aandelendelen.Db;

namespace Aandelendelen.Caching
{
	public static class DataCache
	{
		public static T GetCacheableObject<T>(string cacheName) where T : ICacheable, new()
		{
			T obj = (T)HttpContext.Current.Cache[cacheName];
			if (obj == null)
			{
				obj = new T();
				obj.CacheThis(cacheName);
			}

			return obj;
		}

		public static int ActiveUsers
		{
			get { return (int)new Query("s_activemembers").Execute(); }
		}

		public static decimal GetSaldo(int userId)
		{
			object obj = new Query("s_saldo", "Id", userId, OleDbType.Integer).Execute();
			return (obj == null ? 0 : (decimal)obj);
		}

		public static decimal InvestedAmount
		{
			get
			{
				string cacheName = "data_investedamount";

				object obj = DataCache.Cache[cacheName];

				decimal investedAmount;

				if (obj == null)
				{
					investedAmount = 100000;

					CacheDependency dependency = new CacheDependency(HttpContext.Current.Server.MapPath("/App_Data/Daily.xml"));

					DataCache.Cache.Insert(cacheName, investedAmount);

					obj = investedAmount;
				}

				return (decimal)obj;
			}
		}


		public static void ClearAll()
		{
			//According to some web resources, we can safely remove items from within the loop, since we are working on a copy of the cache when iterating.
			Cache cache = DataCache.Cache;
			foreach (DictionaryEntry entry in cache)
			{
				cache.Remove((string)entry.Key);
			}
		}

		public static Cache Cache
		{
			get { return HttpContext.Current.Cache; }
		}
	}
}